package com.promise.jokerdream.database

import android.content.Context
import androidx.room.*
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.promise.jokerdream.model.log.ExecutionLog
import com.promise.jokerdream.model.log.ExecutionLogDao

/**
 * 执行日志数据库
 */
@Database(
    entities = [ExecutionLog::class],
    version = 2,
    exportSchema = false
)
@TypeConverters(Converters::class)
abstract class ExecutionLogDatabase : RoomDatabase() {
    
    abstract fun executionLogDao(): ExecutionLogDao
    
    companion object {
        @Volatile
        private var INSTANCE: ExecutionLogDatabase? = null
        
        fun getDatabase(context: Context): ExecutionLogDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    ExecutionLogDatabase::class.java,
                    "execution_log_database"
                )
                .fallbackToDestructiveMigration() // 开发阶段使用，生产环境需要提供Migration
                .build()
                INSTANCE = instance
                instance
            }
        }
    }
}

/**
 * 类型转换器
 */
class Converters {
    @TypeConverter
    fun fromTimestamp(value: Long?): java.util.Date? {
        return value?.let { java.util.Date(it) }
    }

    @TypeConverter
    fun dateToTimestamp(date: java.util.Date?): Long? {
        return date?.time
    }
}
